package acn.spring.shop.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import acn.spring.domain.Category;
import acn.spring.domain.Product;
import acn.spring.service.ShopService;
import acn.spring.shop.viewUtil.PageWrapper;

@Controller
@RequestMapping("/categories")
public class CategoryController extends BaseCategoryController {

	@Autowired
	public CategoryController(ShopService shopService) {
		super(shopService);
	}

	@RequestMapping("/{id}")
	public String getCategory(@PathVariable("id") Category category, Model model,
			@PageableDefault(size = 6, sort = "bestseller") Pageable pageable, HttpServletRequest request,
			@RequestHeader(value = "x-requested-with", required = false) String requestHeader) {

		Page<Product> page = getShopService().getProducts(category, pageable);

		PageWrapper<Product> pageWrapper = new PageWrapper<Product>(page, request.getRequestURI(),
				pageable.getPageSize());
		model.addAttribute("page", pageWrapper);

		model.addAttribute("currentCategoryId", category.getId());

		if (requestHeader == null) {
			return "home";
		} else {
			return "home :: allProducts";
		}

	}
}
